package com.hh.flow.service.impl;

import com.hh.flow.enums.FlowType;
import com.hh.flow.mapper.ExecuteMapper;
import com.hh.flow.service.ExecuteService;
import com.hh.security.utils.SecurityUtils;
import com.hh.system.api.LoginUser;
import com.hh.system.api.domain.SysRole;
import com.monkey.flow.core.DefAppService;
import com.monkey.flow.core.InsAppService;
import com.monkey.flow.core.domain.dto.FlowParams;
import com.monkey.flow.core.domain.entity.FlowInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description:  流程实例impl
 * @author minliuhua
 * @date: 2023/5/29 13:09
 */

@Service
public class ExecuteServiceImpl implements ExecuteService {

    @Resource
    private ExecuteMapper executeMapper;

    @Resource
    private DefAppService defAppService;

    @Resource
    private InsAppService insAppService;

    /**
     * 办理
     * @param id
     * @param conditionValue
     * @param message
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(Long id, String conditionValue, String message)
    {
       LoginUser user = SecurityUtils.getLoginUser();
       FlowParams flowParams = FlowParams.build().flowCode(FlowType.TEST_LEAVE.getKey())
               .createBy(user.getUser().getUserId().toString())
               .nickName(user.getUser().getNickName());
       List<SysRole> roles = user.getUser().getRoles();
       if (Objects.nonNull(roles)) {
           List<String> roleList = roles.stream().map(role -> "role:" + role.getRoleId()).collect(Collectors.toList());
           flowParams.setPermissionFlag(roleList);
       }
        FlowInstance flowInstance = insAppService.skipFlow(id, conditionValue, message, flowParams);
        executeMapper.updateStatus(flowInstance);
        return true;
    }
}
